import { login } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'

const state = {
  token: getToken() || '',
  user: JSON.parse(localStorage.getItem('user')) || ''
}

const mutations = {
  getToken(state, payload) {
    state.token = payload
    setToken(payload)
  },
  getUserInfo(state, info) {
    localStorage.setItem('user', JSON.stringify(info))
  }

}

const actions = {
  // user login
  async login(context, payload) {
    const res = await login(payload)
    // console.log(res.data.user)
    const token = res.data.token.token
    const user = res.data.user
    context.commit('getToken', token)
    context.commit('getUserInfo', user)
    setToken(token)
  },
  logout(context) {
    context.commit('getToken', '')
    context.commit('getUserInfo', {})
    localStorage.removeItem('user')
    removeToken()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

